package com.neuedu.web;

import com.alibaba.fastjson.JSON;
import com.neuedu.utils.EchoUtils;
import com.neuedu.utils.PicEncode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet(name = "ArticleUploadImgServlet",urlPatterns = "/article/uploadimg")
public class ArticleUploadImgServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求参数
        String base = request.getParameter("base");
        // 替换字符串中非图片信息
        base = base.replace("data:image/png;base64,","");
        // 指定保存上传图片的文件夹
        String path = getServletContext().getRealPath(File.separator+"upload");
        // 如果不存在该文件夹
        File file = new File(path);
        if(!file.exists()){
            // 创建该文件夹
            file.mkdir();
        }
        // 上传图片,uuid保证用户上传的图片不重名，将uuid作为图片名
        String uuid = UUID.randomUUID().toString();
        // 指定保存路径
        String strSavePath = path+File.separator+uuid+".jpg";
        // 解析上传
        PicEncode.generateImage(base,strSavePath);
        // 响应ajax请求
        EchoUtils echoUtils = new EchoUtils();
        echoUtils.setCode(1);
        echoUtils.setPath("upload/"+uuid+".jpg");
        // 转json
        //language=JSON
//        String str = "{\"code\": 1,\"path\": "+"\""+echoUtils.getPath()+"\""+"}";
        String str = JSON.toJSONString(echoUtils);
       response.getWriter().println(str);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
